package org.webcamp.questionary.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.webcamp.questionary.dto.AnswerIndex;
import org.webcamp.questionary.dto.Questionary;
import org.webcamp.questionary.dto.QuestionaryProgress;
import org.webcamp.questionary.dto.Score;
import org.webcamp.questionary.services.QuestionaryService;
import org.webcamp.questionary.services.impl.PercentileScore;
import org.webcamp.results.dto.QuestionaryResult;
import org.webcamp.results.services.ResultsService;
import org.webcamp.users.dto.User;

@Controller
public class QuestionaryController {

	private static final String PARAM_PREFIX = "answer";
	private Logger log = Logger.getLogger(getClass());
	private QuestionaryService questionaryService;
	private ResultsService resultsService;

	public void setResultsService(ResultsService resultsService) {
		this.resultsService = resultsService;
	}

	public void setQuestionaryService(QuestionaryService questionaryService) {
		this.questionaryService = questionaryService;
	}

	@RequestMapping("selection")
	public ModelAndView showSelection() {
		return new ModelAndView("selection", "questionaries", questionaryService.getAllQuestionaries());
	}

	@RequestMapping("start_questionary")
	public ModelAndView startQuestionary(@RequestParam(value = "name", required = true) String name, HttpSession session) {
		QuestionaryProgress progress = new QuestionaryProgress();
		Questionary questionary = null;
		for (Questionary q : questionaryService.getAllQuestionaries()) {
			if (q.getName().equals(name)) {
				questionary = q;
				break;
			}
		}
		if (questionary == null) {
			return new ModelAndView("selection", "questionaries", questionaryService.getAllQuestionaries());
		}
		progress.setQuestionary(questionary);
		progress.setCurrentQuestionIndex(0);
		session.setAttribute("progress", progress);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("question", progress.getCurrentQuestion());
		model.put("progress", "0");
		return new ModelAndView("question", model);
	}

	@RequestMapping("question")
	public ModelAndView processNextQuestion(HttpSession session, HttpServletRequest request) {
		// if there's no progress in session then this means our session expired
		QuestionaryProgress progress = (QuestionaryProgress) session.getAttribute("progress");
		if (progress == null) {
			return new ModelAndView("selection");
		}
		List<AnswerIndex> userAnswers = new ArrayList<>();
		for (Object paramName : request.getParameterMap().keySet()) {
			String name = (String) paramName;
			if (name.startsWith(PARAM_PREFIX)) {
				String stringIdx = name.substring(PARAM_PREFIX.length());
				Integer idx = Integer.valueOf(stringIdx);

				AnswerIndex ai = new AnswerIndex();
				ai.setIndex(idx);
				ai.setAnswer(progress.getCurrentQuestion().getAnswers().get(idx));
				userAnswers.add(ai);
			}
		}
		progress.getAnswers().add(userAnswers);

		if (progress.getCurrentQuestionIndex() == progress.getQuestionary().getQuestions().size() - 1) {

			PercentileScore ps = new PercentileScore();
			Score score = ps.evaluate(progress.getQuestionary(), progress.getAnswers());

			User user = (User) session.getAttribute("user");
			QuestionaryResult result = new QuestionaryResult();
			result.setUserId(user.getId());
			result.setDate(new Date());
			result.setQuestionaryName(progress.getQuestionary().getName());
			result.setResult(score.getValue());
			resultsService.addResult(result);

			return new ModelAndView("results", "score", score);
		} else {
			progress.setCurrentQuestionIndex(progress.getCurrentQuestionIndex() + 1);
			int prog = 100 * progress.getCurrentQuestionIndex() / progress.getQuestionary().getQuestions().size();
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("question", progress.getCurrentQuestion());
			model.put("progress", prog);
			return new ModelAndView("question", model);
		}
	}

}
